﻿using Infrastructure;
using Infrastructure.Extensions;
using IP2Region.Ex.Models;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZR.DataCollection.Model;
using ZR.DataCollection.OperationCore.OperationEnum;
using ZR.DataCollection.OperationCore.OperationHelper;
using ZR.Model.Models.ProductionControl;
using ZR.Service.IService.ProductionControl;
using ZR.ServiceCore.Signalr;

namespace ZR.DataCollection.OperationCore.OperationMode
{
    /// <summary>
    /// 所有工位批次码录入
    /// </summary>
    public class BatchCode : OperationInfoBase
    {
        private readonly IBatchBindingService _batchBindingService = App.GetRequiredService<IBatchBindingService>();
        private readonly IHubContext<MessageHub> _hubContext = App.GetRequiredService<IHubContext<MessageHub>>();
        private readonly NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();

        private int collectStatus = 1;

        public BatchCode(int operationType, string stationType) : base(operationType, stationType)
        {
        }

        public override void WorkDetail(ImpParameter imp)
        {
            DataDock? dataDock = imp.objectParam as DataDock;
            //读取配置的操作（读操作、写操作数组）、依次执行
            var keyValuePairs = CurrentCruxPoint(dataDock.LineCode, dataDock.ProductType, dataDock.ItemNo);
            SpotHandle(imp, keyValuePairs);
        }

        public override void SpotHandle(ImpParameter parameter, Dictionary<int, List<OperationPointConfig>> SpotGroup)
        {
            try
            {
                foreach (var SpotInfo in SpotGroup)
                {
                    switch (SpotInfo.Key)
                    {
                        case (int)DataOperateEnum.Read:
                            ReadFunction(parameter, SpotInfo.Value);
                            break;

                        case (int)DataOperateEnum.Write:
                            SpotInfo.Value.ForEach(x =>
                            {
                                if (collectStatus.Equals(1))
                                {
                                    parameter.PLCDetail.WriteValue(x.ItemNo, Convert.ToInt16(collectStatus));
                                }
                                if (collectStatus.Equals(2))
                                {
                                    parameter.PLCDetail.WriteValue(x.ItemNo, Convert.ToInt16(collectStatus));
                                }
                            });
                            break;

                        case (int)DataOperateEnum.Verify:
                            break;

                        default:
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error("数据保存Error", ex);
            }
        }

        public async void ReadFunction(ImpParameter parameter, List<OperationPointConfig> operations)
        {
            DataDock? data = parameter.objectParam as DataDock;
            foreach (var pointInfo in operations)
            {
                //批次条码：一个请求点位只会有一个批次条码
                string batchCode = parameter.PLCDetail.ReadValue(pointInfo.ItemNo).ToString();
                BatchBinding batch = await _batchBindingService.QueryByClauseAsync(qbc => qbc.StationCode.Equals(data.StationCode) && qbc.BatchNo.Equals(Convert.ToInt32(pointInfo.GroupName)));
                if (batch.IsNullOrZero())
                {
                    BatchBinding binding = new BatchBinding();
                    binding.BatchNo = Convert.ToInt32(pointInfo.GroupName);
                    binding.BatchCode = batchCode;
                    binding.LineCode = data.LineCode;
                    binding.StationCode = data.StationCode;
                    binding.UpdateTime = DateTime.Now;
                    var result = await _batchBindingService.InsertAsync(binding);
                    if (result <= 0)
                    {
                        collectStatus = 2;
                    }
                }
                else
                {
                    batch.BatchCode = batchCode;
                    batch.UpdateTime = DateTime.Now;
                    var result = await _batchBindingService.InsertOrUpdateAsync(batch);
                    if (!result)
                    {
                        collectStatus = 2;
                    }
                }
            }
        }
    }
}